package utils;

import android.util.Log;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * Created by Administrator on 2018/9/27/027.
 */

/**
 * 上传文件到服务器
 *
 * @author henry
 *
 */
public class SocketHttpRequester {


    private static final String TAG = "uploadFile";
    // 超时时间
    private static final int TIME_OUT = 100 * 1000;
    // 设置编码
    private static final String CHARSET = "UTF-8";

    /**
     * android上传文件到服务器
     *
     * @param file
     *            需要上传的文件
     * @param RequestURL
     *            请求的rul
     * @return 返回响应的内容
     *
     *  [urlRequest setHTTPMethod:@"POST"];
    [urlRequest setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [urlRequest setValue:@"multipart/form-data; boundary=heima" forHTTPHeaderField:@"Content-Type"];


    NSMutableData * body = [NSMutableData data];
    NSData * data = [NSData dataWithContentsOfFile:createPath];


    //    2> 文件参数
    [body appendData:HMEncode(@"--heima\r\n")];
    [body appendData:HMEncode(@"Content-Disposition: form-data; name=\"file\"; filename=\"test123.png\"\r\n")];
    [body appendData:HMEncode(@"Content-Type: application/zip\r\n")];

    [body appendData:HMEncode(@"\r\n")];
    [body appendData:data];
    [body appendData:HMEncode(@"\r\n")];

    //    3> 结束标记 ：参数结束的标记
    [body appendData:HMEncode(@"--heima--\r\n")];
    [urlRequest setHTTPBody:body];
     */
    public static String uploadFile(File file, String RequestURL) {
        String result = null;
        // 边界标识 随机生成
        String BOUNDARY = "heima";
        String PREFIX = "--", LINE_END = "\r\n";
        // 内容类型
        String CONTENT_TYPE = "multipart/form-data";

        try {

            URL url = new URL(RequestURL);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(TIME_OUT);
            conn.setConnectTimeout(TIME_OUT);
            // 允许输入流
            conn.setDoInput(true);
            // 允许输出流
            conn.setDoOutput(true);
            // 不允许使用缓存
            conn.setUseCaches(false);
            // 请求方式
            conn.setRequestMethod("POST");
            // 设置编码
            conn.setRequestProperty("Charset", CHARSET);
            conn.setRequestProperty("connection", "keep-alive");
            conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";charset=UTF-8;boundary="
                    + BOUNDARY);

            if (file != null && file.exists()) {
                /**
                 * 当文件不为空，把文件包装并且上传
                 */
                DataOutputStream dos = new DataOutputStream(
                        conn.getOutputStream());
                StringBuffer sb = new StringBuffer();
                sb.append(PREFIX);
                sb.append(BOUNDARY);
                sb.append(LINE_END);
                /**
                 * 这里重点注意： name里面的值为服务器端需要key 只有这个key 才可以得到对应的文件
                 * filename是文件的名字，包含后缀名的 比如:abc.png
                 */
                sb.append("Content-Disposition: form-data; name=\"file\"; filename=\""
                        + file.getName() + "\"" + LINE_END);
                sb.append("Content-Type: application/zip;charset= UTF-8" + LINE_END);
                sb.append(LINE_END);
                dos.write(sb.toString().getBytes());
                FileInputStream is = new FileInputStream(file);
                byte[] bytes = new byte[1024 * 1024];
                int len = 0;
                while ((len = is.read(bytes)) != -1) {
                    dos.write(bytes, 0, len);
                }
                is.close();
                dos.write(LINE_END.getBytes());
                byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END)
                        .getBytes();
                dos.write(end_data);
                dos.flush();
                /**
                 * 获取响应码 200=成功 当响应成功，获取响应的流
                 */
                int res = conn.getResponseCode();
                Log.e(TAG, "response code:" + res);
                // if(res==200)
                // {
                Log.e(TAG, "request success");
                InputStream input = conn.getInputStream();
                StringBuffer sb1 = new StringBuffer();
                int ss;
                while ((ss = input.read()) != -1) {
                    sb1.append((char) ss);
                }
                result = sb1.toString();
                result = new String(result.getBytes("iso8859-1"), "utf-8");
                Log.e(TAG, "result : " + result);
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;}
        return result;
    }

}